/**
 * \file flashMemory.c
 * \brief Driver du controleur mémoire flash.
 * \author {Mengxuan.Z Nicolas.M}
 * \version 0.10
 * \date 12 mars 2011
 *
 * Fichier d'implémentation des APIs pour lire et écrire
 * dans la mémoire flash
 *
 * La mémoire est divisée en 2 segments d'information de 128 octets. 
 * Leure adresse va de 0x1000 à 0x107f pour le segment B et 
 * de 0x1080 à 0x10ff pour le segment A.
 * 
 * On utilise le segment A.
 * 
 */



#include  <msp430x14x.h>
#include <io.h>
#include <signal.h>
#include <iomacros.h>
#include <stdio.h>
#include <stdlib.h>

#include "flashMemory.h"

#include "../utils/utils.h"

void writeUINT (char* addr, unsigned int data)
{
	char valChar[2];
	valChar[1] = data & 0x00ff;
	valChar[0] = (data >> 8) &0x00ff;
	write_flashMemory (addr,valChar,2);
}

unsigned int readUINT(char* addr)
{
	unsigned int val = 0;
	char *valChar = &val;
	valChar[0] = read_flashMemory(addr++);
	valChar[1] = read_flashMemory(addr);
	return val;
}

void write_flashMemory (char* addr,char* value,unsigned int size)
{
  char* Flash_ptr;
unsigned int i;
_DINT();
  Flash_ptr =addr;                         // Initialize Flash pointer
  FCTL1 = FWKEY + ERASE;                           // Clear Lock bit
  FCTL3 = FWKEY;                           // Clear Lock bit
  *Flash_ptr = 0; 
  
  FCTL1 = FWKEY + WRT; 

  
  for (i=0; i<size; i++)
  {
    *Flash_ptr = *value;                   // Write value to flash
     Flash_ptr++;
     value++; 
  }

  FCTL1 = FWKEY;                            // Clear WRT bit
  FCTL3 = FWKEY + LOCK;                     // Set LOCK bit
	_EINT();
}

char read_flashMemory(char* addr)
{
  char *Flash_ptr;                       // Segment pointer
  Flash_ptr = addr;                      // Initialize Flash pointer

  return *Flash_ptr;
}

void clean_flashMemory(void)
{
  char *Flash_ptr;                          // Flash pointer
  unsigned int i;

  Flash_ptr = (char *) 0x1080;              // Initialize Flash pointer
  FCTL1 = FWKEY + ERASE;                    // Set Erase bit
  FCTL3 = FWKEY;                            // Clear Lock bit
  *Flash_ptr = 0;                           // Dummy write to erase Flash segment

  FCTL1 = FWKEY;                            // Clear WRT bit
  FCTL3 = FWKEY + LOCK;                     // Set LOCK bit

  Flash_ptr = (char *) 0x1000;              // Initialize Flash pointer
  FCTL1 = FWKEY + ERASE;                    // Set Erase bit
  FCTL3 = FWKEY;                            // Clear Lock bit
  *Flash_ptr = 0;                           // Dummy write to erase Flash segment

  FCTL1 = FWKEY;                            // Clear WRT bit
  FCTL3 = FWKEY + LOCK;  
}

